package downloader

import (
	"gitee.com/Luna-CY/hui-hui/internal/toolbox/downloader"
	"gitee.com/Luna-CY/hui-hui/server/http/response"
	"github.com/gin-gonic/gin"
	"time"
)

type TasksResponse struct {
	response.BaseListResponse[Task]
}

type Task struct {
	Id               string `json:"id" validate:"required"`                    // 任务ID
	State            int    `json:"state" validate:"required" enums:"1,2,3,4"` // 任务状态：下载中、失败、完成、取消
	Message          string `json:"message" validate:"required"`               // 状态描述
	StartTime        int64  `json:"start_time" validate:"required"`            // 开始时间
	EndTime          int64  `json:"end_time" validate:"required"`              // 结束时间，状态为失败、完成、取消时有效
	Filename         string `json:"filename" validate:"required"`              // 文件名称
	FileSize         int64  `json:"file_size" validate:"required"`             // 文件大小，单位字节
	DownloadSize     int64  `json:"download_size" validate:"required"`         // 已下载字节数，状态为下载中时有效
	Target           int    `json:"target" validate:"required"`                // 保存的目标位置
	Expired          int64  `json:"expired" validate:"required"`               // 文件过期时间，状态为完成时有效
	LocalFileRemoved bool   `json:"local_file_removed" validate:"required"`    // 服务端缓存文件是否已被移除
}

func (cls *Downloader) Tasks(_ *gin.Context) (int, any, error) {
	var data = cls.downloader.Tasks()

	var res = TasksResponse{}
	res.Total = int64(len(data))
	res.Data = make([]Task, 0)

	for _, task := range data {
		var item = Task{}
		item.Id = task.Id
		item.State = int(task.State)
		item.Message = task.Message
		item.StartTime = task.StartTime.Unix()
		item.Filename = task.Filename
		item.FileSize = task.FileSize
		item.DownloadSize = task.DownloadSize
		item.LocalFileRemoved = task.LocalFileRemoved
		item.Target = int(task.Target)

		if downloader.TaskTargetResources == task.Target {
			task.LocalFileRemoved = true
		}

		if downloader.TaskStateDownloading != task.State {
			item.EndTime = task.EndTime.Unix()
		}

		if downloader.TaskStateComplete == task.State {
			item.Expired = task.EndTime.Add(task.Timeout).Unix()

			// 过期后文件可能被删除，不允许下载文件
			if time.Now().Unix() >= item.Expired {
				item.LocalFileRemoved = true
			}
		}

		res.Data = append(res.Data, item)
	}

	return response.Ok, res, nil
}
